<template>
  <div class>
    <!-- 面包屑 -->
    <breadcrumb>
      <span slot="main">用户管理</span>
      <span slot="main_a">用户列表</span>
    </breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索与添加 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="gerUserList()">
            <el-button slot="append" icon="el-icon-search" @click="gerUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户信息展示 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-row>
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="showEditDialog(scope.row.id)"
              ></el-button>
              <el-button type="danger" icon="el-icon-delete" circle @click="open(scope.row.id)"></el-button>
              <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-s-tools" circle @click="setRole(scope.row)"></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页显示 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <!-- 对话框中的校验内容 -->
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="telnumber">
          <el-input v-model="ruleForm.telnumber"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="aditDialogVisible" width="50%" @close="editDialogClosed">
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="aditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="
        editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoleId" filterable placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MyComponent',
  props: {},
  data() {
    // 验证邮箱的正则表达式
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }

    // 验证手机号的正则表达式
    var checkMobile = (rule, value, callback) => {
      const regnum = /^(0|86|17951)?([13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regnum.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号'))
    }
    return {
      // 状态显示
      value: true,
      // 获取用户列表参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 用户信息列表
      userList: [],
      total: 0,
      // 打开添加用户的对话框
      dialogVisible: false,
      // 打开修改用户信息对话框
      aditDialogVisible: false,
      // 控制分配角色对话框
      setRoleDialogVisible: false,
      // 查询用户数据
      editForm: [],
      // 需要被分配角色的角色信息
      userInfo: {},
      // 获取所有角色列表
      rolesList: [],
      // 下拉菜单已选中的信息
      selectedRoleId: '',
      // 对话框数据
      ruleForm: {
        name: '',
        password: '',
        email: '',
        telnumber: ''
      },
      // 对话框数据校验
      rules: {
        name: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        telnumber: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.gerUserList()
  },
  methods: {
    // 获取用户信息列表
    async gerUserList() {
      let res = await this.$axios.get('users', { params: this.queryInfo })
      // console.log(res)

      if (res.data.meta.status !== 200) {
        return this.$message.error('获取失败！')
      }
      // this.$message.success('获取成功！')

      this.userList = res.data.data.users
      this.total = res.data.data.total
    },
    // 监听 pagessize 改变的事件
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.queryInfo.pagesize = val
      this.gerUserList()
    },
    // 监听页码值 pagenum
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.queryInfo.pagenum = val
      this.gerUserList()
    },
    // 改变用户状态
    async userStateChanged(userinfo) {
      // console.log(userinfo)
      let uid = userinfo.id // 获取用户id
      let mg_state = userinfo.mg_state //获取用户状态
      // console.log(uid, mg_state)
      let res = await this.$axios.put(`users/${uid}/state/${mg_state}`)
      if (res.data.meta.status !== 200) {
        // 所点击的效果取反，则就是未点击状态
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败！')
      }
      this.$message.success('更新用户状态成功！')
      // console.log(res)
      // 重新获取用户列表数据
      this.gerUserList()
    },
    //监听添加用户对话框的关闭事件并重置
    addDialogClosed() {
      this.$refs.ruleForm.resetFields()
    },
    // 点击按钮添加新用户
    addUser() {
      this.$refs.ruleForm.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        //添加用户请求
        let res = await this.$axios.post('users', {
          username: this.ruleForm.name,
          password: this.ruleForm.password,
          email: this.ruleForm.email,
          mobile: this.ruleForm.telnumber
        })
        // console.log(res)
        if (res.data.meta != 201) this.$message.error('创建失败！')
        this.$message.success('创建成功！')
        this.dialogVisible = false
        this.gerUserList()
      })
    },
    //展示修改用户信息对话框
    async showEditDialog(id) {
      // console.log(id)
      let res = await this.$axios.get(`users/${id}`)
      // console.log(res)
      if (res.data.meta != 200)
        //this.$message.error('获取失败！')
        // this.$message.success('获取成功！')
        this.editForm = res.data.data
      this.aditDialogVisible = true
    },
    // 监听修改对话框的关闭事件
    editDialogClosed() {
      this.$refs.ruleForm.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      // 1.进行数据的验证
      this.$refs.ruleForm.validate(
        //2.判断其准确性
        async valid => {
          // console.log(valid)
          if (!valid) return
          let res = await this.$axios.put(`users/${this.editForm.id}`, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          if (res.data.meta.status !== 200) {
            this.$message.error('更新用户信息失败！')
          }
          this.aditDialogVisible = false
          this.gerUserList()
          this.$message.success('更新用户信息成功！')
        }
      )
    },
    // 显示与隐藏分配角色对话框
    async setRole(userInfo) {
      this.userInfo = userInfo

      // 展示对话之前，获取所有的角色列表
      let res = await this.$axios.get('roles')
      if (res.data.meta.status !== 200) {
        return this.$message.error('获取失败！')
      }
      // console.log(res)

      this.rolesList = res.data.data
      this.setRoleDialogVisible = true
    },
    // 删除用户
    async open(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除用户信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除！')
      }
      let res = await this.$axios.delete(`users/${id}`)
      console.log(res)
      if (res.data.meta.status !== 200) {
        return this.$message.error('删除用户失败！')
      }
      this.$message.success('删除用户成功！')
      this.gerUserList()
    },
    // 点击按钮，分配角色
    async saveRoleInfo() {
      // console.log(this.selectedRoleId)

      if (!this.selectedRoleId) {
        return this.$message.error('请选择需要分配的角色！')
      }
      // console.log(this.userInfo)

      let res = await this.$axios.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })
      // console.log(res)
      if (res.data.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')
      this.gerUserList()
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>

<style scoped lang='less'>
</style>
